package com.sg.common.empty.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.apache.bcel.generic.NEW;

import com.alibaba.fastjson.JSONArray;
import com.sg.common.login.entity.Org;
import com.sg.common.utils.Constant;

public class Conditions2 {
	HttpServletRequest request;
	Map<String, Object> rb;
	public static Conditions2 init(HttpServletRequest request,Map<String, Object> rb) {
		Conditions2 res = new Conditions2();
		res.request = request;
		res.rb=rb;
		return res;
	}

	public String buildSorts() {
		String sortSql = "";
		String sort = Constant.getRbString(rb,"sort");
		if (StringUtils.isNotEmpty(sort)) {
			String[] sorts = StringUtils.split(sort, ",");
			if (sorts.length > 0) {
				sortSql = " order by ";
			}
			int ind = 0;
			while (ind < sorts.length) {
				if (ind > 0) {
					sortSql += ",";
				}
				if (sorts[ind].startsWith("-")) {
					sortSql += sorts[ind].substring(1) + " desc";
				} 
				else {
					sortSql += sorts[ind].substring(1) + " asc";
				}
				ind++;
			}
		}
		return sortSql;
	}

	public String buildLimit() {
		String limitSql = "";
		String page = Constant.getRbString(rb,"page");
		String limit =Constant.getRbString(rb,"limit");
		if (StringUtils.isNotEmpty(page) && StringUtils.isNotEmpty(limit)) {
			Integer pageInt = Integer.valueOf(page);
			Integer limitInt = Integer.valueOf(limit);
			limitSql += " limit " + (pageInt - 1) * limitInt + "," + limitInt;
		}
		return limitSql;
	}


	public ConditionRes buildCon() {
		ConditionRes res = new ConditionRes();
		List<String> pl = new ArrayList<String>();
		String conditionSql = "";

		String route = (String) request.getAttribute("conf.route");
		List<String> conditions = Constant.getStringList(route + ".conditions");
		for (int i = 0; i < conditions.size(); i++) {
			String condition = conditions.get(i);
			String[] split = StringUtils.split(condition, "`");
			if (split.length > 1 && StringUtils.isNotEmpty(split[0])) {
				Object param =null;
				String[] split1=StringUtils.split(split[0], "@");
//				session开头的直接执行下一段程序
				if(!StringUtils.equals("session", split1[0])){
					if (split1.length > 1 && StringUtils.isNotEmpty(split1[0])) {
						if(StringUtils.equals("requestArray", split1[0]))
						{
							param = Constant.getRbList(rb,split1[1]);
							if(Constant.getRbList(rb,split1[1]).size()==0)
							{
								continue;
							}else
							   {
								   param = Constant.getRbList(rb,split1[1]);
							   }
						}
					}else
					{
					   if(StringUtils.isEmpty(Constant.getRbString(rb,split[0])))
					   {
						   continue;
					   }else
					   {
						   param = Constant.getRbString(rb,split[0]);
					   }
					}
				}
				
				if (param!=null) {
					// param = URLDecoder.decode(param, "UTF-8");
					// 网页端传入此参数，则在condition中加入sql语句
					if (!StringUtils.startsWith(split[1], "@")) {
						// String conSql = StringUtils.replace(split[1], "?",
						// param);
							pl.add(String.valueOf(param));
						    conditionSql += " and " + split[1];
					} else {
						String[] ss = StringUtils.split(split[1], ",");
						if (StringUtils.equals("@dateRange", ss[0])) {
							conditionSql += " and " + ss[1] + " >= ? and "
									+ ss[1] + " <= ? ";
							pl.addAll(Arrays.asList(String.valueOf(param).split(" - ")));
						} else if (StringUtils.equals("@like", ss[0])) {
							if(!StringUtils.equals(split1[0],"requestArray")){
								String sqlVariable = split[0];
								if (ss.length > 1) {
									sqlVariable = ss[1];
								}
								conditionSql += " and " + sqlVariable + " like ? ";
								pl.add("%" + param + "%");
							}else{
								if(StringUtils.contains(ss[1], "||")){
									String[] sqlVariable = StringUtils.split(ss[1], "||");
									List<String> array = (List<String>) param;
									for(int j = 0; j<sqlVariable.length; j++){
										if(j==0){
											conditionSql += " and (";
										}else{
											conditionSql += " or (";
										}
										if(array.size()>0){
											for(int l = 0;l <array.size(); l++){
												if(l==0){
													conditionSql += sqlVariable[j] + " like ? ";
												}else{
													conditionSql += " or " + sqlVariable[j] + " like ? ";
												}
												pl.add("%" + array.get(l) +"%");
											}
											conditionSql += ")";
										}
									}
								}else{
									String sqlVariable = split[0];
									if (ss.length > 1) {
										sqlVariable = ss[1];
									}
									List<String> array = (List<String>) param;
									if(array.size()>0){
										conditionSql += " and (";
										for(int l = 0;l <array.size(); l++){
											if(l==0){
												conditionSql += sqlVariable + " like ? ";
											}else{
												conditionSql += " or " + sqlVariable + " like ? ";
											}
											pl.add("%" + array.get(l) +"%");
										}
										conditionSql += ")";
									}
								}
								
							}
						} else if (StringUtils.equals("@dateRange2", ss[0])){
							conditionSql += " and " + ss[1] + " >= ? and "
									+ ss[1] + " <= ? ";
							List<String> dates = (List<String>) param;
							pl.add(dates.get(0));
							pl.add(dates.get(1));
						} 
					}
				}else{
					//TODO 业务内容应从此处分开
					if(StringUtils.equals(split[1], "sessionAttributeRestId")){
						HttpSession session = request.getSession();
						String myRestaurantId = (String)session.getAttribute(Constant.SESSION_MYRESTAURANT);
						if(StringUtils.isNotBlank(myRestaurantId)){
							String[] restIds = myRestaurantId.split(",");
							conditionSql += " and " + split1[1] + " in (";
							for(int l=0; l<restIds.length; l++){
								pl.add(restIds[l]);
								if(l==0){
									conditionSql +=  "?";
								}else{
									conditionSql += "," + "?";
								}
							}
							conditionSql += ")";
						}
					}else if (StringUtils.equals(split[1], "sessionAttributeMyDepOrgId")){
						HttpSession session = request.getSession();
						Org myDepOrg = (Org)session.getAttribute(Constant.SESSION_MYDEPORG);
						if(myDepOrg!=null){
							String myDepOrgId = myDepOrg.getId();
							if(StringUtils.isNotBlank(myDepOrgId)){
								pl.add(myDepOrgId);
								conditionSql += " and " + split1[1] + " = ?";
							}
						}
						
					}else if (StringUtils.equals(split[1], "sessionAttributeMyWorkShopOrgId")){
						HttpSession session = request.getSession();
						Org myWorkShopOrg = (Org)session.getAttribute(Constant.SESSION_MYWORKSHOPORG);
						if(myWorkShopOrg!=null){
							String myWorkShopOrgId = myWorkShopOrg.getId();
							if(StringUtils.isNotBlank(myWorkShopOrgId)){
								pl.add(myWorkShopOrgId);
								conditionSql += " and " + split1[1] + " = ?";
							}
						}
						
					}else if (StringUtils.equals(split[1], "sessionAttributeMyStationOrgId")){
						HttpSession session = request.getSession();
						Org myWorkShopOrg = (Org)session.getAttribute(Constant.SESSION_MYSTATIONORG);
						if(myWorkShopOrg!=null){
							String myWorkShopOrgId = myWorkShopOrg.getId();
							if(StringUtils.isNotBlank(myWorkShopOrgId)){
								pl.add(myWorkShopOrgId);
								conditionSql += " and " + split1[1] + " = ?";
							}
						}
						
					}
				}
			}
		}
		res.setParams(pl.toArray());
		res.setSql(conditionSql);
		return res;
	}
	
	public ConditionRes buildCon(List<String> conditions) {
		ConditionRes res = new ConditionRes();
		List<String> pl = new ArrayList<String>();
		String conditionSql = "";

		
		for (int i = 0; i < conditions.size(); i++) {
			String condition = conditions.get(i);
			String[] split = StringUtils.split(condition, "`");
			if (split.length > 1 && StringUtils.isNotEmpty(split[0])) {
				Object param =null;
				String[] split1=StringUtils.split(split[0], "@");
//				session开头的直接执行下一段程序
				if(!StringUtils.equals("session", split1[0])){
					if (split1.length > 1 && StringUtils.isNotEmpty(split1[0])) {
						if(StringUtils.equals("requestArray", split1[0]))
						{
							param = Constant.getRbList(rb,split1[1]);
							if(Constant.getRbList(rb,split1[1]).size()==0)
							{
								continue;
							}else
							   {
								   param = Constant.getRbList(rb,split1[1]);
							   }
						}
					}else
					{
					   if(StringUtils.isEmpty(Constant.getRbString(rb,split[0])))
					   {
						   continue;
					   }else
					   {
						   param = Constant.getRbString(rb,split[0]);
					   }
					}
				}
				
				if (param!=null) {
					// param = URLDecoder.decode(param, "UTF-8");
					// 网页端传入此参数，则在condition中加入sql语句
					if (!StringUtils.startsWith(split[1], "@")) {
						// String conSql = StringUtils.replace(split[1], "?",
						// param);
							pl.add(String.valueOf(param));
						    conditionSql += " and " + split[1];
					} else {
						String[] ss = StringUtils.split(split[1], ",");
						if (StringUtils.equals("@dateRange", ss[0])) {
							conditionSql += " and " + ss[1] + " >= ? and "
									+ ss[1] + " <= ? ";
							pl.addAll(Arrays.asList(String.valueOf(param).split(" - ")));
						} else if (StringUtils.equals("@like", ss[0])) {
							if(!StringUtils.equals(split1[0],"requestArray")){
								String sqlVariable = split[0];
								if (ss.length > 1) {
									sqlVariable = ss[1];
								}
								conditionSql += " and " + sqlVariable + " like ? ";
								pl.add("%" + param + "%");
							}else{
								if(StringUtils.contains(ss[1], "||")){
									String[] sqlVariable = StringUtils.split(ss[1], "||");
									List<String> array = (List<String>) param;
									for(int j = 0; j<sqlVariable.length; j++){
										if(j==0){
											conditionSql += " and (";
										}else{
											conditionSql += " or (";
										}
										if(array.size()>0){
											for(int l = 0;l <array.size(); l++){
												if(l==0){
													conditionSql += sqlVariable[j] + " like ? ";
												}else{
													conditionSql += " or " + sqlVariable[j] + " like ? ";
												}
												pl.add("%" + array.get(l) +"%");
											}
											conditionSql += ")";
										}
									}
								}else{
									String sqlVariable = split[0];
									if (ss.length > 1) {
										sqlVariable = ss[1];
									}
									List<String> array = (List<String>) param;
									if(array.size()>0){
										conditionSql += " and (";
										for(int l = 0;l <array.size(); l++){
											if(l==0){
												conditionSql += sqlVariable + " like ? ";
											}else{
												conditionSql += " or " + sqlVariable + " like ? ";
											}
											pl.add("%" + array.get(l) +"%");
										}
										conditionSql += ")";
									}
								}
								
							}
						} else if (StringUtils.equals("@dateRange2", ss[0])){
							conditionSql += " and " + ss[1] + " >= ? and "
									+ ss[1] + " <= ? ";
							List<String> dates = (List<String>) param;
							pl.add(dates.get(0));
							pl.add(dates.get(1));
						} 
					}
				}else{
					//TODO 业务内容应从此处分开
					if(StringUtils.equals(split[1], "sessionAttributeRestId")){
						HttpSession session = request.getSession();
						String myRestaurantId = (String)session.getAttribute(Constant.SESSION_MYRESTAURANT);
						if(StringUtils.isNotBlank(myRestaurantId)){
							String[] restIds = myRestaurantId.split(",");
							conditionSql += " and " + split1[1] + " in (";
							for(int l=0; l<restIds.length; l++){
								pl.add(restIds[l]);
								if(l==0){
									conditionSql +=  "?";
								}else{
									conditionSql += "," + "?";
								}
							}
							conditionSql += ")";
						}
					}else if (StringUtils.equals(split[1], "sessionAttributeMyDepOrgId")){
						HttpSession session = request.getSession();
						Org myDepOrg = (Org)session.getAttribute(Constant.SESSION_MYDEPORG);
						if(myDepOrg!=null){
							String myDepOrgId = myDepOrg.getId();
							if(StringUtils.isNotBlank(myDepOrgId)){
								pl.add(myDepOrgId);
								conditionSql += " and " + split1[1] + " = ?";
							}
						}
						
					}else if (StringUtils.equals(split[1], "sessionAttributeMyWorkShopOrgId")){
						HttpSession session = request.getSession();
						Org myWorkShopOrg = (Org)session.getAttribute(Constant.SESSION_MYWORKSHOPORG);
						if(myWorkShopOrg!=null){
							String myWorkShopOrgId = myWorkShopOrg.getId();
							if(StringUtils.isNotBlank(myWorkShopOrgId)){
								pl.add(myWorkShopOrgId);
								conditionSql += " and " + split1[1] + " = ?";
							}
						}
						
					}else if (StringUtils.equals(split[1], "sessionAttributeMyStationOrgId")){
						HttpSession session = request.getSession();
						Org myWorkShopOrg = (Org)session.getAttribute(Constant.SESSION_MYSTATIONORG);
						if(myWorkShopOrg!=null){
							String myWorkShopOrgId = myWorkShopOrg.getId();
							if(StringUtils.isNotBlank(myWorkShopOrgId)){
								pl.add(myWorkShopOrgId);
								conditionSql += " and " + split1[1] + " = ?";
							}
						}
						
					}
				}
			}
		}
		res.setParams(pl.toArray());
		res.setSql(conditionSql);
		return res;
	}

}
